const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    showTime: false, //时间弹窗
    showSheet: false, //选择器弹窗
    currentDate: new Date().getTime(),
    minDate: new Date('1900-02-01').getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    selectStr: '', //选择弹窗绑定的属性
    actions: [],
    userPhoto: '',
    fileList: [],
  },



  // 上传头像
  upHandle() {
    var that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        console.log(res.tempFiles)
        that.setData({
          userPhoto: res.tempFiles[0],
          fileList: res.tempFiles,
        })
        console.log(that.data.userPhoto);
      }
    })
  },



  // 保存
  saveHandle() {
    var user = this.data.user;
    if (user.userImg == null && this.data.userPhoto == '') {
      wx.showToast({
        title: '请上传头像',
        icon: 'none'
      })
      return
    } else if (user.userName == '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    } else if (user.userPhone == '') {
      wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      })
      return
    } else if (!this.validator(user.userPhone)) {
      wx.showToast({
        title: '您的联系方式输入有误  ',
        icon: 'none'
      })
      return
    }

    console.log(user);

    var url = app.globalData.url + "scUser/updateUser",
      that = this;
    wx.showLoading({
      title: '',
    })
    console.log(that.data.fileList);
    console.log(user);
    // return
    if (this.data.userPhoto != '') {
      // if (true) {
      wx.uploadFile({
        filePath: that.data.fileList[0].tempFilePath,
        name: 'file',
        url: url,
        formData: {
          userId: app.globalData.userId,
          userName: user.userName,
          userPhone: user.userPhone,
        },
        success(res) {
          var res = JSON.parse(res.data)
          console.log(res);
          app.globalData.user = res.data
          wx.setStorageSync('user', JSON.stringify(res.data))
          if (res.flag) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '信息保存成功',
              showCancel: false,
              complete: (res) => {
                if (res.confirm) {
                  wx.switchTab({
                    url: '/pages/geren/geren',
                  })
                }
              }
            })
          }
        }
      })
    } else {
      app.wxRequest(url, {
          userId: app.globalData.userId,
          userName: user.userName,
          userPhone: user.userPhone,
        }, res => {
          console.log(res);
          if (res.flag) {
            wx.hideLoading()
            console.log(user);
            var newUser = app.globalData.user
            newUser.userName = user.userName
            newUser.userPhone = user.userPhone
            app.globalData.user = newUser
            wx.setStorageSync('user', JSON.stringify(newUser))
            console.log(app.globalData.user);
            wx.showModal({
              title: '提示',
              content: '提交成功',
              showCancel: false,
              complete: (res) => {
                if (res.confirm) {
                  wx.switchTab({
                    url: '/pages/geren/geren',
                  })
                }
              }
            })
            console.log(that.data);
          }
        },
        err => {
          console.log(err);
        })
    }
    console.log(user);
  },

  jsGetAge(strBirthday) {
    var returnAge;
    var strBirthdayArr = strBirthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];

    var d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();

    if (nowYear == birthYear) {
      returnAge = 0; //同年 则为0岁
    } else {
      var ageDiff = nowYear - birthYear; //年之差
      if (ageDiff > 0) {
        if (nowMonth == birthMonth) {
          var dayDiff = nowDay - birthDay; //日之差
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          var monthDiff = nowMonth - birthMonth; //月之差
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
      } else {
        returnAge = -1;
      }
    }

    return returnAge;

  },

  // 验证手机号 
  validator: function (val) {
    return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(val) || /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/.test(val);
  },

  // 输入框编辑
  inputHandle(e) {
    var str = e.currentTarget.dataset.flag
    var val = e.detail.value
    this.setData({
      [str]: val
    })
  },

  // 选择出生日期
  showTimeHandle() {
    this.setData({
      showTime: true
    })
  },
  // 关闭时间选择
  onClose() {
    this.setData({
      showTime: false
    })
  },

  // 确认日期
  confirmTime(event) {
    console.log(event);
    var date = new Date(event.detail)
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var strDate = Y + M + D;
    console.log(strDate);
    var str = 'user.birth',
      str1 = 'user.age';
    this.setData({
      [str]: strDate,
      showTime: false,
      [str1]: this.jsGetAge(strDate)
    });
  },
  // 选择框
  onChange(event) {
    var str = event.currentTarget.dataset.flag
    this.setData({
      [str]: event.detail
    });
  },
  // 显示选择弹窗
  showSelect(e) {
    console.log(e);
    var str = e.currentTarget.dataset.flag;
    this.setData({
      actions: this.data.doctorList,
      selectStr: str,
      showSheet: true
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var user = app.globalData.user;
    console.log(user);
    if (user.userName == null) {
      wx.showToast({
        title: '请完善您的个人信息',
        icon: 'none'
      })
      user.userName == ''
    }
    if (user.userPhone == null) {
      user.userPhone == ''
    }
    if (user.userImg == null) {
      user.userImg == ''
    }
    this.setData({
      user
    })
    console.log(this.data);

    console.log(app.globalData.user);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})